Vista Goodies in C++: Monitoring the Computer's Power Status 您所在的位置:网站首页 burning app Vista Goodies in C++: Monitoring the Computer's Power Status

Vista Goodies in C++: Monitoring the Computer's Power Status

2023-07-05 05:03| 来源: 网络整理| 查看: 265

Download demo project - 62 KB Contents Introduction Power Schemes and Power Sources in Vista Registering for Power Notifications How the Sample App Registers Handling Power Notifications How the Sample App Handles Notifications Conclusion References Copyright and License Revision History Introduction

In this Vista Goodies article, I'll demonstrate how to monitor the computer's power status using new notifications that were added to Vista. For apps that may be CPU- or graphics-intensive — such as audio encoders, games, and media players — the ability to monitor the power status lets them be intelligent about power consumption when running on laptops. For example, a media player might automatically stop playing when the battery level falls below 15%, so the user will have plenty of time to attach a power cord, and won't have to scramble to close or stop the player to preserve what little power is left.

This article is written for the RTM version of Vista, using Visual Studio 2005, WTL 7.5, and the Windows SDK. See the introduction in the first Vista Goodies article for more information on where you can download those components.

This article's sample project is a dialog-based app that shows some simple animation. It monitors the computer's power status, updates the display to reflect the current status, and turns off the animation in situations where power conservation is important. For example, here is the dialog showing that the computer is running on AC power:

The "Hello, Bob!" text changes color every second in this case, since the computer isn't in a low-power situation and it's OK to use animation.

Power Schemes and Power Sources in Vista

Vista defines three default power schemes, named Power saver, Balanced, and High performance. Each scheme is a pre-set group of settings that control things like hard disk spin-down time, the maximum CPU speed to use, and so on. You can choose a power scheme using the battery tray icon or the Power Options control panel applet. Here is the tray selector with the Power saver scheme selected:

Vista also has some settings that can be different when the computer is using different power sources: batteries versus AC power. You can, for example, set the monitor to turn off after 3 minutes on batteries, or 15 minutes on AC power. Vista also monitors the battery power remaining, which is expressed as a percentage from 1 to 100.

Registering for Power Notifications

Apps can register to be notified of changes to the power scheme, power source, or battery power. The two APIs involved are RegisterPowerSettingNotification() and UnregisterPowerSettingNotification(). The prototype for RegisterPowerSettingNotification() is:

  HPOWERNOTIFY RegisterPowerSettingNotification( HANDLE hRecipient, LPCGUID PowerSettingGuid, DWORD Flags);

hRecipient is a handle to the object that wants to receive notifications; in our case it's our dialog's HWND. PowerSettingGuid is a GUID that indicates which event we want to be notified of. Flags indicates what type of handle hRecipient is; in this sample code, the handle will always be an HWND, so we'll pass DEVICE_NOTIFY_WINDOW_HANDLE for Flags.

The relevant GUIDs for PowerSettingGuid are:

GUID_POWERSCHEME_PERSONALITY: register for changes in the power scheme GUID_ACDC_POWER_SOURCE: register for changes in the power source GUID_BATTERY_PERCENTAGE_REMAINING: register for changes in the battery power

RegisterPowerSettingNotification() returns an HPOWERNOTIFY, or NULL if an invalid parameter was passed. The HPOWERNOTIFY is only used when unregistering; the actual notifications occur through window messages.

How the Sample App Registers

CMainDlg has three HPOWERNOTIFY members:

  HPOWERNOTIFY m_hPowerSchemeNotify, m_hPowerSourceNotify, m_hBatteryPowerNotify;

OnInitDialog() calls RegisterPowerSettingNotification() once for each type of notification. For example, this code registers for notifications about power scheme changes:

  m_hPowerSchemeNotify = RegisterPowerSettingNotification ( m_hWnd, &GUID_POWERSCHEME_PERSONALITY, DEVICE_NOTIFY_WINDOW_HANDLE ); if ( NULL == m_hPowerSchemeNotify ) ATLTRACE("Failed to register for notification of power scheme changes!\n");

If RegisterPowerSettingNotification() fails, it's not a critical error; the app just won't be notified about that particular event.

Handling Power Notifications

When an app needs to be notified of a power change, the system sends it a WM_POWERBROADCAST message. WM_POWERBROADCAST is not a new message, but in Vista there is a new event code PBT_POWERSETTINGCHANGE and an associated data structure POWERBROADCAST_SETTING. When a PBT_POWERSETTINGCHANGE notification is sent, the message's lParam points to a POWERBROADCAST_SETTING struct, which looks like this:

  typedef struct { GUID PowerSetting; DWORD DataLength; UCHAR Data[1]; } POWERBROADCAST_SETTING;

PowerSetting is a GUID that indicates what type of event occurred. The possible values for this member are the same GUIDs that are passed to RegisterPowerSettingNotification(). The rest of the struct is a variable-length chunk of data that contains the details of the event. This data varies among the different events:

 

PowerSetting value

Data description

GUID_POWERSCHEME_PERSONALITY

A GUID that indicates the active power scheme:

GUID_MAX_POWER_SAVINGS: the Power saver scheme GUID_MIN_POWER_SAVINGS: the High performance scheme GUID_TYPICAL_POWER_SAVINGS: the Balanced scheme

GUID_ACDC_POWER_SOURCE

An int that indicates the power source: 0 for AC power, 1 for batteries, or 2 for short-term batteries (for example, batteries in a UPS).

GUID_BATTERY_PERCENTAGE_REMAINING

An int that indicates the battery power remaining: 1 to 100.

 

How the Sample App Handles Notifications

CMainDlg has a few members that keep track of the current power situation:

  enum EPowerScheme { pwrPowerSaver, pwrMaxPerf, pwrBalanced }; EPowerScheme m_eCurrPowerScheme; bool m_bOnBattery; int m_nBatteryPower; bool m_bUseAnimation;

These members are set to reasonable defaults (balanced scheme, not on batteries, animation on) and are changed in the WM_POWERBROADCAST handler. OnPowerBroadcast() starts by checking the event type, and returning if it's not PBT_POWERSETTINGCHANGE:

  LRESULT CMainDlg::OnPowerBroadcast ( DWORD dwEvent, DWORD dwData ) { // We only care about Vista power setting notifications. if ( PBT_POWERSETTINGCHANGE != dwEvent ) { SetMsgHandled(false); return 0; }

Next, we get a pointer to the POWERBROADCAST_SETTING struct sent with the message, and look at its PowerSetting member to see what event this notification is for. If it's GUID_POWERSCHEME_PERSONALITY, we determine what the new scheme is. If the scheme isn't one of the three predefined GUIDs, then we'll assume the scheme is Balanced.

  POWERBROADCAST_SETTING* pps = (POWERBROADCAST_SETTING*) dwData; if ( sizeof(GUID) == pps->DataLength && pps->PowerSetting == GUID_POWERSCHEME_PERSONALITY ) { // This is a power scheme change notification GUID newScheme = *(GUID*)(DWORD_PTR) pps->Data; if ( GUID_MAX_POWER_SAVINGS == newScheme ) { // New scheme: max power savings m_eCurrPowerScheme = pwrPowerSaver; m_cPowerScheme.SetWindowText ( _T("Power saver") ); } else if ( GUID_MIN_POWER_SAVINGS == newScheme ) { // New scheme: min power savings (max perf) m_eCurrPowerScheme = pwrMaxPerf; m_cPowerScheme.SetWindowText ( _T("Max performance") ); } else if ( GUID_TYPICAL_POWER_SAVINGS == newScheme ) { // New scheme: balanced m_eCurrPowerScheme = pwrBalanced; m_cPowerScheme.SetWindowText ( _T("Balanced") ); } else { // Unrecognized scheme, we'll treat this like balanced m_eCurrPowerScheme = pwrBalanced; m_cPowerScheme.SetWindowText ( _T("Balanced") ); } }

For power source notifications, we determine whether the new source is batteries or AC power:

  else if ( sizeof(int) == pps->DataLength && pps->PowerSetting == GUID_ACDC_POWER_SOURCE ) { // This is a power source change notification int nPowerSrc = *(int*)(DWORD_PTR) pps->Data; m_bOnBattery = (0 != nPowerSrc); m_cPowerSource.SetWindowText ( m_bOnBattery ? _T("Battery") : _T("AC power") ); }

Finally, for battery power notifications, we save the new percentage:

  else if ( sizeof(int) == pps->DataLength && pps->PowerSetting == GUID_BATTERY_PERCENTAGE_REMAINING ) { // This is a battery power notification int nPercentLeft = *(int*)(DWORD_PTR) pps->Data; CString sPercentLeft; sPercentLeft.Format ( _T("%d"), nPercentLeft ); m_cBatteryPower.SetWindowText ( sPercentLeft ); m_nBatteryPower = nPercentLeft; }

Now that we've updated the static text controls to reflect the new power state, we determine whether to turn the animation on or off. The app's logic is this:

Turn animation on if: The current scheme is High performance, or The current scheme is Balanced and the computer is not on batteries. Turn animation off if: The current scheme is Balanced and the computer is on batteries, or The current scheme is Power saver, or The computer is on batteries and the battery power is 20% or less (no matter what the current scheme is).

 

  bool bUseAnimation = (pwrMaxPerf == m_eCurrPowerScheme) || (pwrBalanced == m_eCurrPowerScheme && !m_bOnBattery); if ( m_bOnBattery && m_cBatteryPower


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有